package com.woniu.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileUploadController {
    // 从配置文件中注入上传路径
    @Value("${web.upload.path}")
    private String uploadPath;

    @PostMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) {
        File uploadDir = new File(uploadPath);

        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();

        try {
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 4. 生成唯一文件名，防止覆盖
            String newFileName = UUID.randomUUID() + "." + fileExtension;
            File destFile = new File(uploadDir, newFileName);

            file.transferTo(destFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return "上传成功";
    }

}
